﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Xml.Linq;
using System.Text.RegularExpressions;
using ConstellationShow.Function.DocData;
using System.Windows.Media.Imaging;
using System.Collections.ObjectModel;
using Microsoft.Phone.Shell;

namespace ConstellationShow.Pages
{
    public partial class Core : MyPage
    {
        string id = "";  //星座ID
        string url = ""; //初始化URL
        string todayUrl = ""; //拉取今天运程URL
        string name = ""; //星座名称
        ObservableCollection<Famou> lists = null; //明星列表
        int p = 1; //明星列表当前页
        int isnextpage = 1; //明星列表是否有下一页，1为有，0为无

        //初始化
        public Core()
        {
            InitializeComponent();
            Loaded += new RoutedEventHandler(Core_Loaded);
            list.LayoutUpdated += new EventHandler(list_LayoutUpdated);
        }

        //页面加载
        void Core_Loaded(object sender, RoutedEventArgs e)
        {
            id = NavigationContext.QueryString["id"];
            url = Mark.MarkUrl(Url.GetStar);
            url += "&consnum=" + id;
            todayUrl = url + "&type=0";
            _progress.IsVisible = true;
            name = Info.ConvStr(id);
            TitleName.Text = name;
            TitleIcon.Source = new BitmapImage(new Uri("/Images/" + Info.ConvIcon(id), UriKind.Relative));
            SetDoc();
            GetData(todayUrl, 0);

            object o = Com.GetSetting("cons");
            List<Cons> lst = new List<Cons>();
            if (o != null) lst = o as List<Cons>;
            for (int i = 0; i < lst.Count; i++)
            {
                if (id == lst[i].id)
                {
                    ApplicationBarIconButton btn = (ApplicationBarIconButton)ApplicationBar.Buttons[1];
                    btn.IconUri = new Uri("/Images/i_attention.png", UriKind.Relative);
                    btn.Text = "取消关注";
                }
            }
        }

        //类型 0、今日运程；1、明日运程；2、本周运程；3、本月运程；4、本年运程
        void GetData(string _url, int type)
        {
            WebClient webClient = new WebClient();
            webClient.OpenReadCompleted += (_, __) =>
            {
                if (__.Error != null)
                {
                    MessageBox.Show("网络错误，请检查网络是否连接好！");
                    _progress.IsVisible = false; return;
                };
                using (Stream streamResult = __.Result)
                {
                    XElement root = XElement.Load(streamResult);
                    var tests = from el in root.Elements("resultinfo") select el;
                    foreach (var a in tests)
                    {
                        if (a.Attribute("result").Value == "1") //成功
                        {
                            string _allast = ""; string _entast = "";
                            string _lovast = ""; string _estast = "";

                            var allast = from el in root.Elements("allast") select el;
                            var entast = from el in root.Elements("entast") select el;
                            var lovast = from el in root.Elements("lovast") select el;
                            var estast = from el in root.Elements("estast") select el;
                            foreach (var b in allast)
                                _allast = b.Value;
                            foreach (var b in entast)
                                _entast = b.Value;
                            foreach (var b in lovast)
                                _lovast = b.Value;
                            foreach (var b in estast)
                                _estast = b.Value;
                            if (type == 0)
                            {
                                _s1.mark = Convert.ToInt32(_allast);
                                s2.mark = Convert.ToInt32(_entast);
                                s3.mark = Convert.ToInt32(_lovast);
                                s4.mark = Convert.ToInt32(_estast);
                                var shortremark = from el in root.Elements("shortremark") select el;
                                List<string> _shortremark = new List<string>();
                                foreach (var b in shortremark)
                                    _shortremark = Com.ParseLuck(b.Value, 1);
                                txt1.Text = _shortremark[0].Trim();
                                txt2.Text = _shortremark[1].Trim();
                                txt3.Text = _shortremark[2].Trim();
                                txt4.Text = _shortremark[3].Trim() + "\n" + _shortremark[4].Trim();
                                txt5.Text = _shortremark[5].Trim();
                                GetData(url + "&type=1", 1); //加载明日数据
                            }
                            else if (type == 1)
                            {
                                s2_1.mark = Convert.ToInt32(_allast);
                                s2_2.mark = Convert.ToInt32(_entast);
                                s2_3.mark = Convert.ToInt32(_lovast);
                                s2_4.mark = Convert.ToInt32(_estast);
                                GetData(url + "&type=2", 2);
                            }
                            else if (type == 2)
                            {
                                s3_1.mark = Convert.ToInt32(_allast);
                                s3_2.mark = Convert.ToInt32(_entast);
                                s3_3.mark = Convert.ToInt32(_lovast);
                                s3_4.mark = Convert.ToInt32(_estast);
                                _progress.IsVisible = false;
                            }
                        }
                    }
                }
            };
            webClient.OpenReadAsync(new Uri(_url), webClient);
        }

        //轴Changed事件
        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (piv.SelectedIndex == 3 && lists == null)
            {
                lists = new ObservableCollection<Famou>();
                string _url = Mark.MarkUrl(Url.GetFamous) + "&cons=" + Info.ConvStr(id);
                _progress.IsVisible = true;
                GetFamou(_url);
            }
        }

        //拉取名人数据
        void GetFamou(string _url)
        {
            WebClient webClient = new WebClient();
            webClient.OpenReadCompleted += (_, __) =>
            {
                if (__.Error != null)
                {
                    MessageBox.Show("暂无名人数据！");
                    _progress.IsVisible = false; return;
                };
                using (Stream streamResult = __.Result)
                {
                    XElement root = XElement.Load(streamResult);
                    var tests = from el in root.Elements("resultinfo") select el;
                    foreach (var a in tests)
                    {
                        if (a.Attribute("result").Value == "1") //成功
                        {
                            var starinfo = from el in root.Elements("starinfo") select el;
                            foreach (var s in starinfo) //遍历adinfo
                            {
                                Famou f = new Famou();
                                f.Id = s.Element("starid").Value;
                                string img = s.Element("picurl").Value;
                                if (img != null && img.Trim() != "")
                                    f.Image = img;
                                else
                                    f.Image = "/Images/pic.png";
                                f.Name = s.Element("starname").Value;
                                lists.Add(f);
                            }
                            var page = from el in root.Elements("page") select el;
                            foreach (var pe in page) //遍历page
                            {
                                isnextpage = Convert.ToInt32(pe.Attribute("isnextpage").Value);
                                p = Convert.ToInt32(pe.Attribute("p").Value);
                            }
                            if (list.Items.Count == 0) list.DataContext = lists;
                            _progress.IsVisible = false;
                        }
                    }
                }
            };
            webClient.OpenReadAsync(new Uri(_url), webClient);
        }

        //速配按钮事件
        private void BtnPair(object sender, System.Windows.RoutedEventArgs e)
        {
            Button btn = sender as Button;
            string con = btn.CommandParameter.ToString();
            NavigationService.Navigate(new Uri("/Pages/Pair.xaml?id1=" + id + "&id2=" + con, UriKind.Relative));
        }

        //获取档案数据
        void SetDoc()
        {
            string[] str = { };
            if (id == "0")
                str = Info.getBaiYang();
            else if (id == "1")
                str = Info.getJinNiu();
            else if (id == "2")
                str = Info.getShuangZi();
            else if (id == "3")
                str = Info.getJuXie();
            else if (id == "4")
                str = Info.getShiZi();
            else if (id == "5")
                str = Info.getChuNv();
            else if (id == "6")
                str = Info.getTianCheng();
            else if (id == "7")
                str = Info.getTianXie();
            else if (id == "8")
                str = Info.getSheShou();
            else if (id == "9")
                str = Info.getMoJie();
            else if (id == "10")
                str = Info.getShuiPing();
            else if (id == "11")
                str = Info.getShuangYu();

            doc1.Text = str[0];
            doc2.Text = str[1];
            doc3.Text = str[2];
            doc4.Text = str[3];
            doc5.Text = str[4];
            doc6.Text = str[5];
            doc7.Text = str[6];
            doc8.Text = str[7];
            doc9.Text = str[8];
            doc10.Text = str[9];
            doc11.Text = str[10];

            BtnLegend.Content = name + "传说";
            BtnLove.Content = name + "爱情";
            BtnBoy.Content = name + "男生";
            BtnGirl.Content = name + "女生";
            BtnOrigin.Content = name + "起源";
            BtnCharacter.Content = name + "性格";
        }

        //ListBox滚动条下拉时加载数据
        void list_LayoutUpdated(object sender, EventArgs e)
        {
            ScrollViewer scrollViewer = Com.FindChildOfType<ScrollViewer>(list);
            if (scrollViewer != null)
            {
                if (isnextpage == 1 && !_progress.IsVisible &&
                    scrollViewer.VerticalOffset >= scrollViewer.ScrollableHeight &&
                    list.Items.Count > 0)
                {
                    _progress.IsVisible = true;
                    p++;
                    string _url = Mark.MarkUrl(Url.GetFamous) +
                        "&cons=" + Info.ConvStr(id) +
                        "&p=" + p;
                    GetFamou(_url);
                }
            }
        }

        //运程按钮事件
        private void BtnLuck(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;  
            int index = 0;
            if (btn.Content.ToString() == "明日运程") index = 1;
            else if (btn.Content.ToString() == "本周运程") index = 2;
            NavigationService.Navigate(new Uri("/Pages/Luck.xaml?index=" + index + "&id=" + id, UriKind.Relative));
        }

        //文档按钮
        private void DocBtn(object sender, RoutedEventArgs e)
        {
            string index = (sender as Button).Content.ToString().Replace(name, "");
            NavigationService.Navigate(new Uri("/Pages/Doc.xaml?index=" + index + "&id=" + id, UriKind.Relative));
        }

        //明星按钮
        private void list_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            Famou f = (sender as ListBox).SelectedItem as Famou;
            NavigationService.Navigate(new Uri("/Pages/Famous.xaml?id=" + id + "&sid=" + f.Id, UriKind.Relative));
        }

        //设置Bar
        private void Click_Setting(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/Setting.xaml", UriKind.Relative));
        }

        //收藏Bar
        private void Click_Collect(object sender, EventArgs e)
        {
            ApplicationBarIconButton btn = sender as ApplicationBarIconButton;
            if (btn.Text == "关注") //关注
            {
                object o = Com.GetSetting("cons");
                List<Cons> lst = new List<Cons>();
                if (o != null)
                {
                    if ((o as List<Cons>).Count >= 2)
                    {
                        MessageBox.Show("你最多关注2个哦！"); return;
                    }
                    lst = o as List<Cons>;
                }
                lst.Add(new Cons() { id = id, name = name });
                Com.SetSetting("cons", lst);
                btn.IconUri = new Uri("/Images/i_attention.png", UriKind.Relative);
                btn.Text = "取消关注";
            }
            else
            {  //取消关注
                object o = Com.GetSetting("cons");
                if (o != null)
                {
                    List<Cons> lst = o as List<Cons>;
                    for (int i = 0; i < lst.Count; i++)
                        if (id == lst[i].id) lst.RemoveAt(i);
                    Com.SetSetting("cons", lst);
                }
                btn.IconUri = new Uri("/Images/i_add_aton.png", UriKind.Relative);
                btn.Text = "关注";
            }
        }

        //回到主页Bar
        private void Click_Home(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
        }

        //星闻Bar
        private void Click_News(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Pages/News.xaml", UriKind.Relative));
        }
    }

    //名人对象
    public class Famou
    {
        public string Id { get; set; }
        public string Image { get; set; }
        public string Name { get; set; }
    }

}